import qs from 'qs';
import {
  DataProcessUpload,
  DataProcessGetSelect,
  DataProcessGetDataFile,
  DataProcessDeleteFile
} from "@/api/stu/datahandle"
import { ref, reactive, nextTick, onMounted } from "vue"
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { emitter } from "@/utils/mitt";
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
export function usehooks(typeRow) {
  const AstrictFileType = ref<string>(".pdf, .doc, .docx, .xls, .xlsx");
  const refform = ref();
  const upload = ref<UploadInstance>();
  const loading = ref(false);
  const dataList = ref([]);
  const hierarchydatalist = ref([]);
  const Visible = ref(false);
  const Visibletitle = ref("添加");
  const SearchForm = reactive({
    hierarchyname: "",
    filename: ""
  })
  const form = reactive<any>({
    DataProcessFileId: "",
    parent: "",
    file: "",
    fileId: "",
    filename: "",
    webaddress: "",
    datatype: "",
    fileSize: "",
    fileType: "",
    fileUrl: "",
    Type: typeRow,//类型 表格:0 or 文字:1
    IOrE: "1",//类型 新增:1 or 修改:2
  })
  const rules = {
    parent: [
      {
        required: true,
        message: "请选择层级！",
        trigger: ["blur", "change"]
      }
    ],
    file: [
      {
        required: true,
        message: "请选择文件！",
        trigger: ["blur", "change"]
      }
    ],
    filename: [
      {
        required: true,
        message: "请输入文件名称！",
        trigger: ["blur", "change"]
      }
    ],
    webaddress: [
      // {
      //   required: true,
      //   message: "请输入网站地址！",
      //   trigger: ["blur", "change"]
      // }
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          const str = "^(http|ftp|https):\/\/[\\w\-_]+(\\.[\\w\\-_]+)+([\\w\-\\.,@?^=%&:/~\\+#]*[\\w\-\@?^=%&/~\\+#])?$";
          const reg = new RegExp(str);
          if (!reg.test(value)) {
            return callback(new Error('请输入正确的网站地址'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    datatype: [
      {
        required: true,
        message: "请选择数据类型！",
        trigger: ["blur", "change"]
      }
    ],
  }
  const columns = [{
    label: "序号",
    type: "index",
    width: 100
  }, {
    label: "层级名称",
    prop: "folderName"
  }, {
    label: "文件名称",
    prop: "fileName"
  }, {
    label: "网站地址",
    prop: "webPath"
  }, {
    label: "操作",
    fixed: "right",
    width: 180,
    slot: "operation"
  }]
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  });


  // 保存
  async function AddData(row) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        DataprocessFolderId: form.parent,//层级ID
        FileName: form.filename,//文件名称
        WebPath: form.webaddress,//网站地址
        DataType: form.Type == '0' ? form.datatype : '0',//数据类型
        Type: form.Type,//类型 表格:0 or 文章:1
        IOrE: form.IOrE,//类型 新增:1 or 修改:2
        DataProcessFileId: form.DataProcessFileId,// 修改时传所修改内容的ID
        fileUrl: form?.file[0]?.response?.data?.fileUrl || form?.file[0]?.url,
        fileId: form.fileId
      };
      const res = await DataProcessUpload(data);
      if (res.success) {
        ElMessage.success(res.msg);
        GetDataList()
        CloseData(row)
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  // 打开修改
  function HandEdit(row) {
    Visible.value = true;
    if (row?.fileId) {
      Visibletitle.value = '修改'
      nextTick(() => {
        form.IOrE = '2';
        form.fileId = row.fileId;
        form.parent = row.folderId; // 层级
        form.filename = row.fileName;//文件名称
        form.webaddress = row.webPath;//网站地址
        form.datatype = row.dataType//数据类型
        form.fileSize = 0;
        form.DataProcessFileId = row.DataProcessFileId// 修改时传所修改内容的ID
        form.file = [{
          name: row.filePath,
          url: row.filePath
        }];
      })
    } else {
      Visibletitle.value = '添加'
      form.IOrE = '1'
      form.fileId = "";
    }
  }

  // 删除
  async function HandDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const data = qs.stringify({
        dataProcessFileId: row.fileId,
        fileUrl: row.filePath,
        type: typeRow
      })
      const res = await DataProcessDeleteFile(data);
      if (res.success) {
        GetDataList()
        ElMessage.success(res.msg)
      }
      else ElMessage.error(res.msg)
    }).catch(() => { })
  }

  // 上传文件时
  function handleBeforeUpload(file) {
    if (file.size / 1024 / 1024 > 100) {
      ElMessage.warning("文件大小不能超过100M！");
      return false;
    }
    form.fileSize = file.size;
  }

  // 上传文件成功
  function handleSuccessUpload(file) {
    if (file.data) {
      form.fileType = file.data.fileType
    } else {
      ElMessage.error(file.msg);
      setTimeout(() => {
        form.file = ""
      }, 500)
    }
  }


  function CloseData(row) {
    row.resetFields()
    Visible.value = false;
  }


  // 获取数据列表 （层级）
  async function GetHierarchyDataList() {
    const res = await DataProcessGetSelect();
    // 添加时
    if (res.success) {
      hierarchydatalist.value = res?.data?.items;
    } else {
      ElMessage.error(res.msg)
    }
  }


  // 获取数据列表
  async function GetDataList() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      folderId: SearchForm.hierarchyname,
      fileName: SearchForm.filename,
      type: typeRow
    }
    const res = await DataProcessGetDataFile(data);
    // 添加时
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount;
    } else {
      ElMessage.error(res.msg)
    }
  }
  function handleCurrentChange() {
    GetDataList()
  }
  function handleSizeChange() {
    GetDataList()
  }
  onMounted(() => {
    GetHierarchyDataList()
    GetDataList()
  })
  return {
    form,
    rules,
    upload,
    Visible,
    loading,
    dataList,
    columns,
    refform,
    SearchForm,
    pagination,
    Visibletitle,
    AstrictFileType,
    hierarchydatalist,
    handleCurrentChange,
    handleBeforeUpload,
    handleSuccessUpload,
    GetDataList,
    HandEdit,
    HandDelete,
    AddData,
    CloseData,
    handleSizeChange
  }
}
